import React,{Component} from 'react';
import Header from "../../components/header/header";
import Footer from "../../components/footer/footer";
import {Route,Redirect,Switch} from 'react-router-dom'
import Login from "../../pages/login/login";
import Reg from "../../pages/reg/reg";
import Home from "../../pages/home/home";
import Detail from "../../pages/detail/detail";
import Follow from "../../pages/follow/follow";
import Column from "../../pages/column/column";
import User from "../../pages/user/user";
import NoPage from "../../pages/no-page/no-page";
import UcLoading from "../../components/loading/uc-loading";
import pubsub from 'pubsub-js';

export default class Default extends Component {

  state = {
    bNav:true,
    bFoot:true,
    bLoading:true
  };

  constructor(props){
    super(props);
    // 订阅token
    // pubsub.subscribe('事件名',函数(事件名，传入的数据))
    this.token = pubsub.subscribe('update_loading', (msg,bl)=>{
      this.setState({bLoading:bl})
    });

  }

  static getDerivedStateFromProps(nextProps,nextState){

    let path = nextProps.location.pathname;

    // console.log(111,path)

    if (/home|follow|column/.test(path)){
      return {bNav:true,bFoot:true}
    }
    if (/detail|login|reg/.test(path)){
      return {bNav:false,bFoot:false}
    }

    if (/user/.test(path)){
      return {bNav:false,bFoot:true}
    }

    return null;
  }

  componentWillUnmount(){
    //取消指定订阅
    pubsub.unsubscribe(this.token);  
  }

  render(){
    let {bNav,bFoot,bLoading} = this.state;
    return (
      <div>
        <UcLoading spinning={bLoading}/>

        { bNav && <Header/>}

        <Switch>
          <Route path="/home" component={Home}/>
          <Route path="/follow" component={Follow}/>
          <Route path="/column" component={Column}/>
          <Route path="/login" component={Login}/>
          <Route path="/reg" component={Reg}/>
          <Route path="/user" component={User}/>
          <Route path="/detail/:_id" component={Detail}/>
          <Redirect exact from="/" to="/home" />
          <Route component={NoPage} />
        </Switch>

        { bFoot && <Footer/>}
      </div>
    )
  }
}